<template>
  <div class="comments-section">
    <h3 class="section-title">评论 ({{ comments.length }})</h3>
    
    <!-- 评论输入框 -->
    <div class="comment-form">
      <img :src="currentUser?.avatar || '/avatars/default.png'" class="user-avatar" alt="用户头像">
      <div class="input-wrapper" 
           :class="{ 'focused': isInputActive }" 
           @click="isInputActive = true"
           @focusout="handleFocusOut"
      >
        <textarea 
          v-model="newComment"
          placeholder="写下你的评论..."
          :rows="textareaRows"
          @focus="handleFocus"
        ></textarea>
        <div class="form-actions" v-show="isInputActive">
          <button class="cancel-btn" @click="cancelComment">取消</button>
          <button 
            class="submit-btn" 
            :disabled="!newComment.trim()"
            @click="submitComment"
          >
            发布评论
          </button>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="loading" class="loading">
      <i class="fas fa-spinner fa-spin"></i> 加载评论中...
    </div>
    
    <div v-else class="comments-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <img :src="comment.author_avatar" :alt="comment.author_name" class="user-avatar">
        <div class="comment-content">
          <div class="comment-header">
            <router-link 
              :to="{ name: 'userProfile', params: { id: comment.user_id }}"
              class="author-name"
            >
              {{ comment.author_name }}
            </router-link>
            <span class="comment-time">{{ formatDate(comment.create_time) }}</span>
          </div>
          <p class="comment-text">{{ comment.content }}</p>
          <div class="comment-actions">
            <button class="action-btn" @click="replyToComment(comment)">
              <i class="fas fa-reply"></i>
              回复
            </button>
          </div>
        </div>
      </div>

      <div v-if="!comments.length" class="no-comments">
        暂无评论，快来抢沙发吧~
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useArticleStore } from '../stores/articleStore'
import { useUserStore } from '../stores/userStore'
import { useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const articleStore = useArticleStore()
const userStore = useUserStore()

const textareaRows = ref(1)
const newComment = ref('')
const loading = ref(false)
const comments = ref([])
const isInputActive = ref(false)

// 获取当前用户信息
const currentUser = computed(() => userStore.currentUser)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载评论
const loadComments = async () => {
  loading.value = true
  try {
    const articleId = Number(route.params.id)
    console.log("测试点一",route.params.id);
    
    const result = await articleStore.fetchComments(articleId)
    console.log('组件收到的数据:', result)
    comments.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载评论失败:', error)
  } finally {
    loading.value = false
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) return
  
  // 检查用户是否登录
  if (!userStore.isLogin) {
    if (confirm('请先登录后再发表评论')) {
      router.push('/login')
    }
    return
  }
  
  try {
    await articleStore.addComment({
      article_id: Number(route.params.id),
      content: newComment.value.trim()
    })
    
    // 重新加载评论
    await loadComments()
    
    // 清空输入框
    cancelComment()
  } catch (error) {
    console.error('提交评论失败:', error)
  }
}

// 取消评论
const cancelComment = () => {
  newComment.value = ''
  isInputActive.value = false
  textareaRows.value = 1
}

// 回复评论
const replyToComment = (comment) => {
  newComment.value = `@${comment.author_name} `
  textareaRows.value = 3
}

// 处理输入框获得焦点
const handleFocus = () => {
  isInputActive.value = true
  textareaRows.value = 3
}

// 处理失去焦点
const handleFocusOut = (event) => {
  // 检查点击是否在输入框区域内
  const wrapper = event.currentTarget
  const relatedTarget = event.relatedTarget
  
  if (!wrapper.contains(relatedTarget) && !newComment.value.trim()) {
    isInputActive.value = false
    textareaRows.value = 1
  }
}

// 初始加载评论
onMounted(loadComments)
</script>

<style scoped>
.comments-section {
  margin-top: 32px;
  padding-top: 32px;
  border-top: 1px solid var(--border-color);
}

.section-title {
  font-size: 18px;
  color: var(--text-color);
  margin-bottom: 24px;
}

.comment-form {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.input-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: all 0.2s;
}

.input-wrapper.focused {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.1);
}

textarea {
  width: 100%;
  padding: 0;
  border: none;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  outline: none;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.submit-btn {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  background: none;
  border: 1px solid var(--border-color);
}

.submit-btn {
  background: var(--primary-color);
  color: white;
  border: none;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.comment-item {
  display: flex;
  gap: 16px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.author-name {
  font-weight: 500;
  color: var(--primary-color);
  text-decoration: none;
}

.comment-time {
  font-size: 12px;
  color: var(--text-light);
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: var(--text-color);
  margin: 8px 0;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: var(--text-light);
  font-size: 12px;
  cursor: pointer;
  padding: 4px;
}

.action-btn:hover {
  color: var(--primary-color);
}

.loading {
  text-align: center;
  padding: 20px;
  color: var(--text-light);
}

.no-comments {
  text-align: center;
  padding: 32px;
  color: var(--text-light);
  font-size: 14px;
}
</style> 